import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../pages/Login'
import Home from '../pages/Home'
import Detail from '../pages/Detail'

// home子路由
import Homes from '../pages/home/Homes'
import Recommend from '../pages/home/Recommend'
import App from '../pages/home/App'
import My from '../pages/home/My'

let router = new VueRouter({
    // 路由模式 ==> 默认是hash
    // mode
    mode: "history",
    routes: [
        // 重定向
        // 从哪来 ==>  到哪去
        {
            path: "/",
            redirect: "/home"
        },
        {
            path: "/login",
            component: Login
        },
        {
            path: "/home",
            component: Home,
            children: [
                {
                    path: "/home",
                    redirect: "/home/homes"
                },
                {
                    path: "homes",
                    component: Homes
                },
                {
                    path: "recommend",
                    component: Recommend
                },
                {
                    path: "app",
                    component: App
                },
                {
                    path: "my",
                    name: "my",
                    component: My
                }
            ]
        },
        {
            path: "/detail",
            component: Detail
        }
    ]
})

// 全局的路由拦截(进入页面前)  前置函数

router.beforeEach((to, from, next) => {
    // 如果去my, 并且没有登录
    if (to.path === "/home/my" && !sessionStorage.getItem('token')) {
        next('/login')
    } else {
        next()
    }
    // to ==>  去哪
    // from ==> 从哪来
    // next ==> 下一步  next(要去往的页面)

    next()
})


// 全局的路由拦截(进入页面后)  后置函数
// router.afterEach((to, from) => {
//     console.log(to.path, from.path)
// })


Vue.use(VueRouter)

export default router